<template>
  <!--  组织用户管理页面-->
  <div class="box-view">
    <el-row :gutter="15">
      <el-col :span="4" class="left_org">
        <!-- 搜索框 -->
        <organization-tree v-model="deptTree" ref="deptTree" :changeOnSelect='true' placeholder="选择管养单位"
                           @change="selectOrgHandel"></organization-tree>
      </el-col>
      <el-col :span="20">
        <div class="page">
          <div style="padding: 20px 0px 0px 20px">
            <el-breadcrumb separator-class="el-icon-arrow-right">
              <el-breadcrumb-item @click.native="breadClick(item.deptTreeIdList)" v-for="item in deptTree.breadList"
                                  :key="item.name">
                <el-button type="text" class="bread_button_text">{{item.deptName}}</el-button>
              </el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          <el-divider></el-divider>
          <!-- 条件筛选 -->
          <div class="page_filter">
            <div class="select_with_input">
              <el-select v-model="selectModel" placeholder="请选择" style="width: 100px">
                <el-option
                  v-for="item in typeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
              <el-input v-model.trim="searchModel" clearable placeholder="请输入"></el-input>
            </div>
            <!-- 启用状态 -->
            <el-select v-model="form.validFlag" clearable placeholder="请选择启用状态">
              <el-option
                v-for="item in EnumSysFlagList"
                :key="item.code"
                :label="item.name"
                :value="item.code">
              </el-option>
            </el-select>

            <el-button class="common_btn-defalut" icon="el-icon-search" @click="form.page=1;queryList()">搜索</el-button>
          </div>
          <div class="page_main">
            <el-button icon="el-icon-plus" @click.stop="handleAdd" class="common_btn-small">添加账号</el-button>
            <!-- table -->
            <div class="common_btnBox">
              <i class="iconfont iconzongshu icon-size"></i>
              总数：{{form.total}}
            </div>
            <el-table
              :data="tableList"
              border>
              <el-table-column
                label="序号"
                fixed
                width="80">
                <template slot-scope="scope">
                  {{getIndex(scope.$index)}}
                </template>
              </el-table-column>
              <el-table-column prop="loginName" min-width="160" label="登录名"></el-table-column>
              <el-table-column prop="userName" min-width="120" label="姓名"></el-table-column>
              <el-table-column prop="userTypeName" min-width="120" label="用户类型"></el-table-column>
              <el-table-column prop="phone" width="140" label="手机号"></el-table-column>
              <el-table-column width="110" prop="validFlagName" label="启用状态">
                <template slot-scope="scope">
                  <!-- ,0正常，1锁定 -->
                  <span class="user_status" :class="{active: scope.row.validFlag}">{{scope.row.validFlagName}}</span>
                </template>
              </el-table-column>
              <el-table-column show-overflow-tooltip min-width="220" label="关联角色">
                <template slot-scope="scope">
                  <el-tag class="item_tag" v-for="item in scope.row.roleList" :key="item.id" type="success" size="mini"
                          effect="dark">{{ item.name }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="operator" min-width="120" label="创建人"></el-table-column>
              <!--              <el-table-column min-width="200" label="关联工程">-->
              <!--                <template slot-scope="scope">-->
              <!--                  {{showProjectName(scope.row)}}-->
              <!--                </template>-->
              <!--              </el-table-column>-->
              <el-table-column prop="createTime" width="180" label="更新时间">
                <template slot-scope="scope">{{scope.row.createTime | formatTimer}}</template>
              </el-table-column>
              <el-table-column label="操作" fixed="right" width="220">
                <template slot-scope="scope">
                  <button class="btn_edit" @click="handleEdit(scope.row)">编辑</button>
                  <button class="btn_edit" @click="_handleRelated(scope.row)">关联角色</button>
                  <!--                <button class="btn_edit" @click="_handleRelatedProject(scope.row)">关联工程</button>-->
                  <el-popconfirm
                    confirmButtonText='确认'
                    cancelButtonText='取消'
                    icon=""
                    :title="_getSwitchInfo(scope.row.validFlag)"
                    @confirm="_setStatus(scope.row)"
                  >
                    <button
                      slot="reference"
                      :class="scope.row.status ? 'btn_edit' : 'btn_delete'">
                      {{ scope.row.validFlag | getStatusBtnMap }}
                    </button>
                  </el-popconfirm>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页器 -->
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="form.page"
              :page-size="form.pageSize"
              :page-sizes="[10, 20, 30, 40,50,60,70,80,90,100]"
              layout="sizes, prev, pager, next"
              :total="form.total">
            </el-pagination>
          </div>
          <!-- 新增编辑弹窗 -->
          <el-dialog
            :close-on-click-modal="false"
            :title="dialogTitle"
            :visible.sync="isShowDialog"
            :before-close="clearValidate"
            width="600px">

            <!-- 具体form表单 -->
            <el-form label-position="right" ref="form" :rules="rules" :model="currentRow" label-width="90px"
                     class="form_width-200">
              <el-form-item label="登录名" prop="loginName">
                <el-input v-model.trim="currentRow.loginName" placeholder="输入登录名" :disabled="isEditStatus"
                          :maxlength="20" class="init_input-limit" show-word-limit></el-input>
              </el-form-item>
              <el-form-item label="姓名" prop="userName">
                <el-input class="init_input-limit" v-model.trim="currentRow.userName" placeholder="输入姓名" maxlength="20"
                          show-word-limit></el-input>
              </el-form-item>
              <el-form-item label="手机号" prop="phone">
                <el-input class="init_input-limit" v-model.trim="currentRow.phone" placeholder="输入手机号" maxlength="11"
                          show-word-limit></el-input>
              </el-form-item>

              <el-form-item label="账号类型" prop="type">
                <!-- 启用状态 -->
                <el-select v-model="currentRow.type" placeholder="选择账号类型">
                  <el-option
                    v-for="item in EnumUserType"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="启用状态" prop="validFlag">
                <!-- 启用状态 -->
                <el-select v-model="currentRow.validFlag" placeholder="选择启用状态">
                  <el-option
                    v-for="item in EnumSysFlagList"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="密码" :prop="isEditStatus ? null : 'password'">
                <el-input v-model.trim="currentRow.password" placeholder="输入密码" type="password"></el-input>
              </el-form-item>
              <el-form-item label="确认密码" prop="repeat" :required="!isEditStatus">
                <el-input v-model.trim="currentRow.repeat" placeholder="输入密码" type="password"></el-input>
              </el-form-item>
            </el-form>
            <!-- 操作按钮 -->
            <span slot="footer" class="dialog-footer">
              <el-button class="common_btn-white" @click="clearValidate">取消</el-button>
              <el-button class="common_btn-defalut" type="primary" @click="validateForm">确定</el-button>
            </span>
          </el-dialog>

          <!-- 关联角色弹窗 -->
          <el-dialog
            title="关联角色"
            :visible.sync="isShowRelateDialog"
            width="500px">
            <!-- 具体form表单 -->
            <div class="relate_checkbox">
              <el-checkbox :indeterminate="isIndeterminate" :value="isRelateCheckAll" @change="_handleCheckAll">全选
              </el-checkbox>
              <el-checkbox-group v-model="currentRow.roleList" @change="_handleCheckedChange">
                <el-checkbox v-for="item in roleList" :label="item.id" :key="item.id">{{item.name}}</el-checkbox>
              </el-checkbox-group>
            </div>
            <!-- 操作按钮 -->
            <span slot="footer" class="dialog-footer">
              <el-button class="common_btn-white" @click="_closeRelateRole">取消</el-button>
              <el-button class="common_btn-defalut" type="primary" @click="_submitRelateRole">确定</el-button>
            </span>
          </el-dialog>

          <project-dialog ref="project" @update="queryList"></project-dialog>

        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import {CHECK_PASSWORD, CHECK_REPEAT} from './validator'
  import {
    accountAdd,
    accountQuery,
    accountQueryRoleList,
    accountrelRoles,
    accountUpdate
  } from '@/services/model/authority-mgmt'
  import Format from '@/utils/format'
  import OrganizationTree from '@/components/organization-tree/all'
  import {filterEmpty} from '@/services/request'
  import ProjectDialog from './modules/project-dialog'
  import cryptoJs from "crypto-js";
  import Enums from '@/utils/enums'

  // 初始的搜索参数
  const INIT_PARAMS = {
    phone: '',
    name: '',
    username: '',
    email: '',
    proxyCode: ''
  }

  export default {
    mixins: [Enums],
    components: {ProjectDialog, OrganizationTree},
    data() {
      return {
        deptTree: {
          breadList: [],//面包屑
          deptTreeId: '',
        },
        form: {
          page: 1,
          pageSize: 10,
          type: 5
        },
        EnumUserType: [
          {
            name: '单位管理员',
            code: 4
          },
          {
            name: '普通用户',
            code: 5
          },
        ],
        searchParams: INIT_PARAMS, // 搜索3个model
        typeOptions: [
          {
            value: 0,
            label: '登录名',
            key: 'loginName'
          },
          {
            value: 1,
            label: '姓名',
            key: 'userName'
          },
          {
            value: 2,
            label: '手机号',
            key: 'phone'
          },
        ],
        rules: {
          loginName: {required: true, message: '请输入登录名'},
          userName: {required: true, message: '请输入姓名'},
          validFlag: {required: true, message: '请选择启用状态', trigger: 'change'},
          // phone: { required: true, validator: CHECK_PHONE },
          // email: { validator: CHECK_EMAIL },
          password: {required: true, validator: CHECK_PASSWORD},
          repeat: {validator: CHECK_REPEAT.bind(this)}
        },
        selectModel: 0, // 下拉选择model
        searchModel: '', // 搜索框model
        tableList: [],

        isShowDialog: false, // 是否显示弹窗
        isShowRelateDialog: false, // 关联角色弹窗
        // 关联工程项目弹窗
        isShowProjectDialog: false,
        currentRow: {}, // 新增数据
        roleList: [], // 角色列表
        // indeterminate 属性用以表示 checkbox 的不确定状态，一般用于实现全选的效果
        isIndeterminate: true,
        cityList: [],
        provinceModel: '',
        cityModel: '',
        checked: true,
        // 启用状态枚举
        EnumSysFlagList: []
      }
    },
    computed: {
      // 弹窗的title
      dialogTitle() {
        return this.currentRow.id ? '编辑账号' : '新增账号'
      },
      // true  为编辑   false  accountQueryRoleList
      isEditStatus() {
        return !!this.currentRow.id
      },
      // 关联角色弹窗中的全选标志位
      isRelateCheckAll() {
        return this.currentRow.roleList?.length === this.roleList.length && this.roleList.length > 0
      }
    },
    filters: {
      // 时间格式化
      formatTimer(timer) {
        return Format(new Date(timer), 'yyyy-MM-dd hh:mm:ss')
      },
      // 0正常，1锁定
      getStatusBtnMap(type) {
        return type ? '停用' : '启用'
      }
    },
    methods: {
      //面包屑跳转
      breadClick(deptTreeId) {
        this.$refs.deptTree.changeBread(deptTreeId)
      },
      //组织机构组件回调
      selectOrgHandel() {
        this.$forceUpdate()
        this.form.deptTreeId = this.deptTree.deptTreeId
        this.queryList()
      },
      // 显示关联名称
      showProjectName(row) {
        return row.projectList?.map(x => x.name).join('，')
      },
      /**
       * 点击停用、启用切换文本
       * status 0正常，1锁定
       */
      _getSwitchInfo(status) {
        return status ? '停用后，账号无法登录本平台，确认停用？' : '启用该账号？'
      },
      // 根据选择的3个类型设置不同的model
      _setFormModel() {
        let init = INIT_PARAMS
        let item = this.typeOptions.find(x => x.value === this.selectModel)
        this.searchParams = {...init, [item.key]: this.searchModel}
        this.form = {...this.form, ...this.searchParams}
      },
      // 关闭弹窗之关联角色
      _closeRelateRole() {
        this.isShowRelateDialog = false
      },
      // 关联角色提交
      async _submitRelateRole() {
        const params = {
          roleIdList: this.currentRow.roleList,
          userId: this.currentRow.id
        }
        await accountrelRoles(params)
        this.isShowRelateDialog = false
        this.$notify({
          type: 'success',
          title: '提示',
          message: '修改成功'
        })
        this.queryList()
      },
      // 勾选全部
      _handleCheckAll(val) {
        this.currentRow.roleList = val ? this.roleList.map(x => x.id) : []
        this.isIndeterminate = false
      },
      _handleCheckedChange(value) {
        this.currentRow.roleList = value
        let checkedCount = value.length
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.roleList.length
      },
      // 点击关联菜单
      _handleRelated(row) {
        // console.log(row)
        this.currentRow = {id: row.id, roleList: row.roleList.map(x => x.id)}
        this.isShowRelateDialog = true
      },
      // 关联项目
      _handleRelatedProject(row) {
        this.$refs.project.showDialog(row)
      },
      // 停用、启用 设置用户状态
      _setStatus(row) {
        // 0  1 取反
        let Negate = a => (a + 1) % 2
        this.currentRow = {id: row.id, validFlag: Negate(row.validFlag)}
        this.submitData()
      },
      // 获取当前的序号
      getIndex(index) {
        let param = (this.form.page - 1) * this.form.pageSize + index + 1
        return param
      },
      // 分页大小改变
      handleSizeChange(val) {
        this.form.pageSize = val
        this.queryList()
      },


      // 当前页码改变
      handleCurrentChange(val) {
        this.form.page = val
        this.queryList()
      },
      // 关闭弹窗之前清楚表单校验提示
      clearValidate() {
        this.$refs.form.clearValidate()
        this.isShowDialog = false
      },
      // 表单提交
      validateForm() {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.currentRow = filterEmpty(this.currentRow)
            this.submitData()
          }
        })
      },
      encryptByDES(message, key) {
        var keyHex = cryptoJs.enc.Utf8.parse(key);
        var encrypted = cryptoJs.DES.encrypt(message, keyHex, {
          mode: cryptoJs.mode.ECB,
          padding: cryptoJs.pad.Pkcs7
        })
        return encrypted.ciphertext.toString();
      },
      // 新增编辑提交数据
      async submitData(fromTree) {
        // 根据ID判断使用新增还是编辑
        let action = this.currentRow.id ? accountUpdate : accountAdd
        const {password, repeat} = this.currentRow
        const DATA = {
          ...this.currentRow,
          password: password ? this.encryptByDES(password, 'interface.jgkj').toUpperCase() : null,
          repeat: repeat ? this.encryptByDES(repeat, 'interface.jgkj').toUpperCase() : null
        }
        let res = await action(DATA)
        if (res.code === 200) {
          this.$notify({
            type: 'success',
            title: '提示',
            message: this.currentRow.id ? '修改成功' : '添加成功'
          })
          if (fromTree) {
            this.isShowRelateDialog = false
          }
          this.isShowDialog = false
          this.queryList()
        }
        return res
      },
      // 新增数据
      handleAdd() {
        this.currentRow = {
          validFlag: this.EnumSysFlagList[0]?.code,
          organizationId: this.form.deptTreeId,
          type: 5,//默认普通账号
        }
        this.isShowDialog = true
        this.$nextTick(() => {
          this.$refs.form.clearValidate()
        })
      },
      /**
       * row  当前操作行的对象
       */
      handleEdit(row) {
        this.currentRow = {...row, password: '', repeat: ''}
        this.isShowDialog = true
        this.$nextTick(() => {
          this.$refs.form.clearValidate()
        })
      },
      async queryList() {
        // 先根据选择设置查询参数
        this._setFormModel()
        let res = await accountQuery(this.form)
        if (res.code === 200) {
          this.tableList = res.data?.records || []
          this.form.size = Number(res.data?.size)
          this.form.total = Number(res.data?.total)

        }
      },
      // 查询当前用户绑定的角色
      async queryRoleList() {
        let res = await accountQueryRoleList({page: 1, pageSize: 100})
        this.roleList = res.data.records
      }
    },
    mounted() {
      // 启用状态枚举
      this.queryDictList(['EnumSysFlag'], ['EnumSysFlagList'])

    },
    activated() {
      this.queryList()
      // 获取当前用户的角色列表
      this.queryRoleList()
    }
  }
</script>
<style lang="less" scoped>
  .bread_button_text {
    padding-right: 0px;
    font-size: 18px;
    font-weight: 600;
    color: #1990FE;
  }

  .user_status {
    &::before {
      content: '';
      margin-right: 6px;
      display: inline-block;
      width: 6px;
      height: 6px;
      border-radius: 50%;
      background-color: #969997;
    }

    &.active::before {
      background-color: #0DC26B;
    }
  }

  /deep/ .relate_checkbox {
    .el-checkbox {
      margin-bottom: 30px;

      .el-checkbox__label {
        width: 100px;
      }
    }
  }

  /deep/ .dialog_area {
    .el-dialog__header {
      padding-bottom: 0;
    }
  }

  .area_filter {
    .el-select {
      margin-right: 10px;
    }
  }

  .area_choose {
    display: flex;
    margin-top: 30px;

    .choose_left {
      flex-shrink: 0;
      width: 330px;
      border-right: 1px solid #E4E7ED;
      padding-right: 30px;
    }

    .choose_right {
      padding-left: 30px;
      flex-shrink: 0;
      width: 330px;
    }

    .choose_top {
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-bottom: 12px;
      border-bottom: 1px solid #EBEEF5;

      span {
        color: #303133;
        font-weight: bold;
        font-family: PingFangSC-Medium, PingFang SC;
      }

      .top_right {
        color: #606266;

        &.el-button {
          padding: 0;
        }
      }
    }
  }

  .choose_ul {
    padding-top: 16px;
    height: 100%;

    .choose_li {
      cursor: pointer;
      padding: 0 12px 0 9px;
      width: 100%;
      height: 32px;
      display: flex;
      align-items: center;
      justify-content: space-between;

      em {
        display: flex;
        align-items: center;
        font-size: 13px;
        color: #303133;

        .el-icon-check {
          color: #0DC26B;
          margin-right: 5px;
        }
      }

      i {
        font-size: 15px;
      }

      .el-icon-circle-plus-outline {
        display: none;
        color: #0DC26B;
      }

      .el-icon-circle-close {
        display: none;
        color: #F56C6B;
      }

      &:hover {
        background-color: #F2F6FC;

        i {
          display: block;
        }
      }

      &.disable {
        em {
          color: #C0C4CC;
        }

        .el-icon-circle-plus-outline {
          display: none !important;
        }
      }
    }
  }

  .margin_l-16 {
    margin-left: 16px;
  }

  .init_input-limit /deep/ input {
    padding-right: 45px;
  }

  .item_tag {
    margin-left: 6px;

    &:first-child {
      margin-left: 0;
    }
  }

</style>



